package com.atguigu.publisher.controller;

import com.alibaba.fastjson.JSON;
import com.atguigu.publisher.bean.*;
import com.atguigu.publisher.service.OrderDetailService;
import com.atguigu.publisher.service.OrderService;
import com.atguigu.publisher.service.PublisherService;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 实现具体StringBoot业务
 *
 * @author WangJX
 * @version 1.0
 * @date 2019/11/27 18:25
 */
@RestController
public class PublisherController {

    @Autowired
    private PublisherService publisherService;

    @Autowired
    private OrderService orderService;


    @Autowired
    private OrderDetailService orderDetailService;

    //求dau日活
    @GetMapping("realtime-total")
    public String getRealtimeTotal(@RequestParam("date") String date) {
        Long dauTotal = publisherService.getDauTotal(date);
        //获取mysql订单总数
        Double orderTotal = orderService.getOrderTotal(date);

        //对数据进行分装
        List<DauBean> list = new ArrayList<>();
        DauBean dauBean1 = new DauBean("dau", "新增日活", Long.valueOf(dauTotal));
        DauBean dauBean2 = new DauBean("new_mid", "新增设备", Long.valueOf(233L));
        DauBean dauBean3 = new DauBean("order_amount", "新增交易额", Double.valueOf(orderTotal));
        list.add(dauBean1);
        list.add(dauBean2);
        list.add(dauBean3);

        return JSON.toJSONString(list);
    }

    //分时统计
    @GetMapping("realtime-hour")
    public String getRealtimeHour(@RequestParam("id") String id,
                                  @RequestParam("date") String date) {
        if (id.equalsIgnoreCase("dau")) {
            //查询今天需要查询寻的数据
            Map<String, String> todayDauHour = publisherService.getDauHour(date);

            //查询昨天的数据
            String yd = getYd(date);
            Map<String, String> ydDauHour = publisherService.getDauHour(yd);

            Map<String, Map<String, String>> map = new HashMap();
            map.put("yesterday", ydDauHour);
            map.put("today", todayDauHour);

            return JSON.toJSONString(map);
        } else if (id.equalsIgnoreCase("order_amount")) {
            Map orderDauHourTd = orderService.getOrderDauHour(date);

            //查询昨天的数据
            String yd = getYd(date);
            Map orderDauHourYd = orderService.getOrderDauHour(yd);

            Map<String, Map<String, String>> map = new HashMap();
            map.put("yesterday", orderDauHourYd);
            map.put("today", orderDauHourTd);
            return JSON.toJSONString(map);
        } else {
            return null;
        }


    }


    @GetMapping("sale_detail")
    public String getSaleDetail(@RequestParam("date") String date,
                                @RequestParam("keyword") String keyword,
                                @RequestParam("size") int pageSize,
                                @RequestParam("startpage") int pageNo) {

        //从impl中获取查询数据
        Map<String, Object> saleDetail = orderDetailService.getSaleDetail(date, keyword, pageSize, pageNo);

        //获取总数
        double total = Double.parseDouble(String.valueOf(saleDetail.get("total")));

        //获取聚合年龄
        List<GroupByAggs> groupby_age = (ArrayList<GroupByAggs>)saleDetail.get("groupby_age");
        Long age_20ct=0L;
        Long age20_30ct=0L;
        Long age30_ct=0L;
        for (Object o : groupby_age) {
            GroupByAggs groupByAggs = (GroupByAggs) o;
            int age = Integer.parseInt(groupByAggs.getKey());
            int count = Integer.parseInt(String.valueOf(groupByAggs.getCount()));
//            int count = (int)groupByAggs.getCount();
//            System.out.println(age + " count:" + count);

            age30_ct += age >= 30 ? count : 0;
            age20_30ct += (age < 30 && age > 20) ? count : 0;
            age_20ct += age <= 20 ? count : 0;
        }

        double male20Ct = Math.round(age_20ct * 1000D / total) / 10D;
        double male20_30Ct = Math.round(age20_30ct * 1000D / total) / 10D;
        double male30Ct = Math.round(age30_ct * 1000D / total) / 10D;

        //放入一个Option，一边后面JSON输出
        List<Option> listAge = new ArrayList<>();

        Option groupByAggs20 = new Option("20岁以下", male20Ct);
        Option groupByAggs20_30 = new Option("20岁到30岁", male20_30Ct);
        Option groupByAggs30 = new Option("30岁及以上", male30Ct);
        listAge.add(groupByAggs20);
        listAge.add(groupByAggs20_30);
        listAge.add(groupByAggs30);


        //获取聚合性别
        List<GroupByAggs> groupby_gender = (ArrayList<GroupByAggs>)saleDetail.get("groupby_gender");
        Long mm=0L;
        Long ff=0L;
        for (GroupByAggs groupByAggs : groupby_gender) {
            String gender = groupByAggs.getKey();
            long count = Long.parseLong(String.valueOf(groupByAggs.getCount()));

//            System.out.println(gender + " count: " + count);

            mm += gender.equalsIgnoreCase("M") ? count : 0L;
            ff += gender.equalsIgnoreCase("F") ? count : 0L;
        }

        double mmD = Math.round(mm * 1000D / total) / 10D;
        double ffD = Math.round(ff * 1000D / total) / 10D;

        List<Option> listGender = new ArrayList<>();

        //放入一个Option，一边后面JSON输出
        Option mmMale = new Option("女", mmD);
        Option ffMale = new Option("男", ffD);
        listGender.add(ffMale);
        listGender.add(mmMale);


        List<Stat> result = new ArrayList<>();
        Stat groupByAggs = new Stat("年龄占比", listAge);
        Stat groupByGender = new Stat("性别占比", listGender);
        result.add(groupByAggs);
        result.add(groupByGender);


        //获取查询的具体数据
        List<OrderDetail> detail = (List<OrderDetail>)saleDetail.get("detail");

        //对数据进行封装
        SaleResult saleResult = new SaleResult(total, result, detail);


        return JSON.toJSONString(saleResult);
    }




    /**
     * 求yesterday
     *
     * @param date
     * @return
     */
    private String getYd(String date) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date today = format.parse(date);
            //使用DateUtils工具类求昨天
            Date yesterday = DateUtils.addDays(today, -1);
            return format.format(yesterday);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }





    //测试JSON解析
    public static void main(String[] args) {
/*        List<DauBean> list = new ArrayList<>();
        DauBean dauBean1 = new DauBean("dau", "新增日活", 11L);
        DauBean dauBean2 = new DauBean("dau", "新增日活", 233L);
        list.add(dauBean1);
        list.add(dauBean2);

        System.out.println(JSON.toJSONString(list));

        Map<String, Map<String, String>> map = new HashMap();
        Map<String, String> map1 = new HashMap<>();
        map1.put("11", "383");
        map1.put("12", "123");
        map1.put("17", "88");
        map.put("yesterday", map1);

        System.out.println(JSON.toJSONString(map));*/
    }



}
